package com.self.member.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.alicloud.sms.ISmsService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.common.model.Config;
import com.self.common.service.ConfigService;
import com.self.member.constant.MemberConstant;
import com.self.member.mapper.SmsMapper;
import com.self.member.model.Sms;
import com.self.member.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmsServiceImpl extends ServiceImpl<SmsMapper, Sms> implements SmsService {

    @Autowired
    private ISmsService iSmsService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    
    @Override
    public boolean sendMsg(Sms sms) {
        log.info("发送短信{}", JSON.toJSONString(sms, true));
        SendSmsRequest request = buildSmsRequest(sms);
        try {
            SendSmsResponse sendSmsResponse = iSmsService.sendSmsRequest(request);
            log.info("发送的结果为{}", JSON.toJSONString(sendSmsResponse, true));
            String code = sendSmsResponse.getCode();
            if ("OK".equals(code)) { // 发送成功,否则失败
                sms.setStatus(1);
                return save(sms);
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("短信发送失败：{}",e);
        }
        return false;
    }

    /**
     * 构建发送短信的请求对象
     *
     * @param sms
     * @return
     */
    private SendSmsRequest buildSmsRequest(Sms sms) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(sms.getMobile()); //发送给谁
        Config one = configService.findByCode(MemberConstant.SMS_SIGN);
        Assert.notNull(one,"短信签名配置不存在");
        sendSmsRequest.setSignName(one.getValue()); // 设置签名
        Config temp = configService.findByCode(sms.getTemplateCode());
        Assert.notNull(temp,"短信模板不存在");
        sendSmsRequest.setTemplateCode(temp.getValue()); // 模板的Code--动态改变
        String numbers = RandomUtil.randomNumbers(6);
        //放入缓存中
        redisTemplate.opsForValue().set(MemberConstant.CACHE_SMS_PROFIX+sms.getTemplateCode()+":"+sms.getMobile(),numbers,2, TimeUnit.MINUTES);
        JSONObject param = new JSONObject();
        param.put("code",numbers);
        sendSmsRequest.setTemplateParam(param.toString());
        String desc = temp.getDesc(); //  sign:您的验证码${code}，该验证码5分钟内有效，请勿泄漏于他人！
        sms.setContent(one.getValue()+":"+desc.replaceAll("\\$\\{code\\}",numbers)); // 最后短信的内容
        return sendSmsRequest;
    }
}
